package com.hankol.newretail

import android.app.AlertDialog
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.toast
import com.baselibrary.manager.DialogManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.utils.ScreenUtils.dip2px
import com.baselibrary.view.MyCircleProgress
import com.baselibrary.view.SpacesVerticalDec

import com.baselibrary.activity.BaseActivity
import com.hankol.newretail.adapter.EvaluationConfigAdapter
import com.hankol.newretail.adapter.EvaluationUploadImageVideoAdapter
import com.hankol.newretail.arouter.NewRetailHelp
import com.hankol.newretail.bean.AddEvaluationBean
import com.baselibrary.bean.MediaInfo
import com.hankol.newretail.bean.Serv
import com.hankol.newretail.databinding.ActivityPublishEvaluationBinding
import com.hankol.newretail.utils.RetailDialogUtils
import com.hankol.newretail.viewmodel.EvaluationViewModel
import com.media.publish.utils.UploadMediaUtils
import com.media.revision.RevisionMediaActivity
import com.media.utils.WineryAboutUtils
import com.xinlan.imageeditlibrary.EditImgMainActivity
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import kotlin.collections.ArrayList
import kotlin.collections.List
import kotlin.collections.MutableList
import kotlin.collections.arrayListOf
import kotlin.collections.emptyList
import kotlin.collections.mutableListOf

/**
 *@author:hanke
 *2022/9/5
 *desc:
 */
@Route(path = ActivityRouter.NEW_RETAIL.PUBLISH_EVALUATION)
class PublishEvaluationActivity : BaseActivity(), View.OnClickListener, EvaluationUploadImageVideoAdapter.OnItemClickListener {
    private lateinit var dataBinding: ActivityPublishEvaluationBinding
    private lateinit var viewModel: EvaluationViewModel
    private lateinit var mImageVideoAdapter: EvaluationUploadImageVideoAdapter
    private lateinit var mEvaluationConfigAdapter: EvaluationConfigAdapter
    private var servList: ArrayList<Serv> = ArrayList()
    private var mMediaPathList = ArrayList<MediaInfo>()
    private var mMediaUrlList = ArrayList<MediaInfo>()
    private lateinit var submitBean: AddEvaluationBean
    private var rewardScore = 0
    private val mNewRetailHelp = ActivityRouter.getARouterInterface<NewRetailHelp>(ActivityRouter.NEW_RETAIL.NEW_RETAIL_HELP)
    private var productInfoId = 0;
    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_publish_evaluation
    }

    override fun init() {
        SensorsDataManager.instance.productEvaluateSee()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        bundle?.let {
            if (ARouterUtils.parseParams(it, "productInfoId")[0].checkNotNull()) {
                productInfoId = ARouterUtils.parseParams(it, "productInfoId")[0].toInt()
            }
        }
        setStatusBarHeight(R.color.color_F9F9F9)
        StatusBarUtil.setStatusBarDarkTheme(this, true)
        dataBinding = getDataBinding<ActivityPublishEvaluationBinding>()
        viewModel = getActivityViewModelProvider(this).get(EvaluationViewModel::class.java)
        initView()
        initListener()
        initObserver()
        viewModel.requestEvaluationConfig(productInfoId)
    }

    private fun initObserver() {
        viewModel.evaluationConfigBeanLD.observe(this, Observer {
            if (it.checkNotNull()) {
                rewardScore = it.rewardScore
                dataBinding.tvPublishEvaluationTip.text = "完成商品评价，可获得${it.rewardScore}酒币奖励"
                GlideUtils.loadImg_101(this, it.skuCover, dataBinding.ivSkuCover)
                mEvaluationConfigAdapter.setNewData(it.servList)
                servList = it.servList
            }
        })
        viewModel.addEvaluationBeanLD.observe(this, Observer {
            if (it.checkNotNull()) {
                if (it.success) {//跳转到已评价列表
                    EventBusUtils.sendNotify(MessageBus.msgId_refresh_evaluation_list)
                    DialogManager.showCoinDialog(this, "评价成功", rewardScore)
                    finish()
                }
            }
        })
    }

    private fun initListener() {
        dataBinding.ivBack.setOnClickListener(this)
        dataBinding.tvPublishEvaluation.setOnClickListener(this)
    }

    private fun initView() {
        mImageVideoAdapter = EvaluationUploadImageVideoAdapter(this)
        mEvaluationConfigAdapter = EvaluationConfigAdapter()
        dataBinding.rvImagevideo.addItemDecoration(SpacesRightDec(dip2px(this, 0f)))
        dataBinding.rvImagevideo.addItemDecoration(SpacesVerticalDec(dip2px(this, 3f)))
        dataBinding.rvImagevideo.adapter = mImageVideoAdapter
        dataBinding.rvEvaluationService.adapter = mEvaluationConfigAdapter
        mImageVideoAdapter.setOnClickListener(this)
        dataBinding.etEvaluateContent.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable) {
                dataBinding.tvEvaluationNumber.text = "${s.length}/300"
            }

        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.iv_back -> RetailDialogUtils.showCancelEvaluationDialog(this)
            R.id.tv_publish_evaluation -> checkSubmitLimit()
        }
    }

    override fun onBackPressed() {
        RetailDialogUtils.showCancelEvaluationDialog(this)
    }


    private fun checkSubmitLimit() {
        if (dataBinding.erbPublish.ratingLevel == 0) {
            ToastUtils.showShort(this, "商品评价不能为空")
            return
        }
        if (dataBinding.etEvaluateContent.text.toString().isEmpty()) {
            ToastUtils.showShort(this, "评价内容不能为空")
            return
        }
        if (dataBinding.etEvaluateContent.text.toString().length < 10) {
            ToastUtils.showShort(this, "评价内容需要10字以上")
            return
        }
        for (serv in servList) {
            serv.commentQuestionList = serv.commentQuestionListTemp
            }
        submitBean = AddEvaluationBean(servList, dataBinding.etEvaluateContent.text.toString(), dataBinding.erbPublish.ratingLevel, ArrayList(), productInfoId)
        for (serviceConfig in submitBean.commentConfigList) {
            if (serviceConfig.commentResult == 0) {
                ToastUtils.showShort(this, "${serviceConfig.commentType}评价不能为空")
                return
            }
        }
        if (mMediaPathList.size == 0) {
            viewModel.requestAddEvaluation(GsonUtils.toJson(submitBean))
        } else {
            showLoading()
            uploadMedia()
        }
    }

    private lateinit var countDownTimer: CountDownTimer
    var uploadLoadingDialog: AlertDialog? = null
    fun showLoading() {
        uploadLoadingDialog = PopUtils.uploadLoadingDialog(this@PublishEvaluationActivity, object : PopUtils.ICallback4Progress {
            override fun progressCallback(progress: MyCircleProgress, tvProgress: TextView) {
                countDownTimer = object : CountDownTimer(60000, 3000) {
                    override fun onTick(millisUntilFinished: Long) {
                        val pro = (60000 - millisUntilFinished) / 1000
                        progress.setMax(60)
                        progress.setCurrent(pro.toInt())
                    }

                    override fun onFinish() {}
                }.start()
            }
        })
        if (!uploadLoadingDialog!!.isShowing) {
            uploadLoadingDialog!!.show()
        }
    }

    fun hideLoading() {
        dataBinding.tvPublishEvaluation.isEnabled = true
        countDownTimer.cancel()
        if (uploadLoadingDialog.checkNotNull()) {
            uploadLoadingDialog!!.dismiss()
        }
    }

    private fun uploadMedia() {
        val imgList4Path = mutableListOf<String>()
        val videoList4Path = mutableListOf<MediaInfo>()
        mMediaPathList.forEachIndexed { index, mediaInfo ->
            if (mediaInfo.type == 0) {//图片
                imgList4Path.add(mediaInfo.coverUrl)
            } else {//视频
                videoList4Path.add(mediaInfo)
            }
        }
        if (videoList4Path.size > 0) {
            UploadMediaUtils.uploadVideo(videoList4Path[0].videoUrl, object : UploadMediaUtils.UploadVideoListener {
                override fun onProgress(uploadBytes: Long, totalBytes: Long) {
                }

                override fun onComplete(videoUrl: String?, videoCoverUrl: String?) {
                    val file = File(videoList4Path[0].videoUrl)
                    file.delete()
                    mMediaUrlList.add(MediaInfo(videoCoverUrl.checkValue(), videoUrl.checkValue(), 1))
                    if (imgList4Path.size > 0) {
                        uploadImage(imgList4Path)
                    } else {
                        hideLoading()
                        submitBean.mediaInfoList = mMediaUrlList
                        viewModel.requestAddEvaluation(GsonUtils.toJson(submitBean))
                    }
                }
            })
        } else {
            uploadImage(imgList4Path)
        }
    }

    private fun uploadImage(imgList4Path: MutableList<String>) {
        UploadMediaUtils.uploadImages(imgList4Path as java.util.ArrayList<String>?) { questionRespT ->
            if (questionRespT.checkNotNull()) {
                if (questionRespT!!.data.size > 0) {
                    for (bean in questionRespT.data) {
                        mMediaUrlList.add(MediaInfo(bean.ok, "", 0))
                    }
                }
                for (i in imgList4Path) {
                    val file = File(i)
                    file.delete()
                }
            }
            hideLoading()
            submitBean.mediaInfoList = mMediaUrlList
            viewModel.requestAddEvaluation(GsonUtils.toJson(submitBean))
        }
    }

    override fun onItemClick(pos: Int, list: MutableList<MediaInfo>?) {
        //进入大图
        val urlList = mutableListOf<String>()
        for (datum in list as List<MediaInfo>) {
            urlList.add(if (datum.type == 0) datum.coverUrl else datum.videoUrl)
        }
        seeBigImg(urlList, pos, emptyList())
    }

    override fun onAddItemClick() {
        var isHaveVideo = false
        for (bean in mMediaPathList) {
            if (bean.type == 1) {
                isHaveVideo = true
            }
        }
        WineryAboutUtils.uploadImgVideo(this, !isHaveVideo, mMediaPathList.size, 9)
    }

    override fun onDeleteItemClick(pos: Int, list: MutableList<MediaInfo>?) {
        PopUtils.showOkCancelDialog(this, "确认删除", object : PopUtils.ICallBack {
            override fun clickOk() {
                mMediaPathList.removeAt(pos)
                mImageVideoAdapter.setData(mMediaPathList)
                "删除成功".toast()
                mImageVideoAdapter.notifyDataSetChanged()
            }

            override fun clickCancel() {

            }

        }, false, "确认", "取消")
    }

    private fun seeBigImg(coverUrlList: MutableList<String>, position: Int, descList: List<String>) {
        //查看大图
        val bundle = Bundle()
        bundle.putStringArrayList(Constants.KEY_URLS, coverUrlList as ArrayList<String>)
        bundle.putInt(Constants.KEY_INDEX, position)
        bundle.putStringArrayList(Constants.KEY_COMMENT_CONTENT, if (descList.size == 0) ArrayList<String>() else descList as ArrayList<String>)
        bundle.putStringArrayList(Constants.KEY_COMMENT_TITLE, arrayListOf())
        ActivityRouter.startActivity(ActivityRouter.WINE_CELLAR.IMG_VIDEO_DETAIL, bundle)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_select_img_video_path_list) {
            AppManager.getAppManager().finishActivity(RevisionMediaActivity::class.java)
            mNewRetailHelp.finishVideoEditActivity()
            AppManager.getAppManager().finishActivity(EditImgMainActivity::class.java)
            if (messageBus.param1 is String) {//视频  mMediaPathList.add(0, WineryCoverBean("", newPath.checkValue(), 1))
                FileUtils.copyVideoFile(messageBus.param1.toString(), object : FileUtils.OnCopyFileListener {
                    override fun onCopyOver(filePath: String?) {
                        mMediaPathList.add(0, MediaInfo("", filePath.checkValue(), 1))
                    }

                    override fun onCopyError() {
                    }

                })
            } else if (messageBus.param1 is List<*>) {//图片
                var list = messageBus.param1 as List<String>
                for (imageItem in list) {
                    mMediaPathList.add(MediaInfo(imageItem, "", 0))
                }
            }
            //选择轮播
            mImageVideoAdapter.setData(mMediaPathList)
            mImageVideoAdapter.notifyDataSetChanged()
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}